<template>
  <div class="app-container dashboard">
        <!-- 顶部装饰线 -->
    <decoration type="flow" :height="5" style="width:100%;margin-bottom:10px;" />
    
    <!-- 欢迎区域 -->
      <div class="welcome">
        <title-box :font-size="32">欢迎使用 Harry 技术管理系统</title-box>
        <div class="welcome-info">
          <el-avatar size="large" src="https://avatars.githubusercontent.com/u/00000000?v=4" />
          <p class="welcome-desc">基于 Vue3 + Vite + TypeScript + Element-Plus + Mockjs 构建</p>
        </div>


              <el-button
        class="fullscreen-btn"
        circle
        @click="toggleFullscreen"
        :title="isFullscreen ? '退出全屏' : '全屏显示'"
      >
        <el-icon>
          <FullScreen v-if="!isFullscreen" />
          <Aim v-else />
        </el-icon>
      </el-button>

      </div>

    <!-- 统计卡片区域 -->
    <el-row :gutter="20" class="mb-2">
      <el-col :span="6">
        <stat-card
          title="用户数"
          :value="stats.userCount"
          variant="primary"
        >
          <template #icon>
            <el-icon><UserFilled /></el-icon>
          </template>
        </stat-card>
      </el-col>
      <el-col :span="6">
        <stat-card
          title="今日访问"
          :value="stats.todayVisit"
          variant="success"
        >
          <template #icon>
            <el-icon><PieChart /></el-icon>
          </template>
        </stat-card>
      </el-col>
      <el-col :span="6">
        <stat-card
          title="系统运行天数"
          :value="stats.systemDays"
          variant="warning"
        >
          <template #icon>
            <el-icon><Timer /></el-icon>
          </template>
        </stat-card>
      </el-col>
      <el-col :span="6">
        <stat-card
          title="待办事项"
          :value="stats.todoCount"
          variant="danger"
        >
          <template #icon>
            <el-icon><List /></el-icon>
          </template>
        </stat-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <border-box type="gradient" variant="primary">
          <div class="chart-container">
            <title-box :font-size="18">访问趋势</title-box>
            <v-chart :option="visitOption" style="height:320px;width:100%;" autoresize />
          </div>
        </border-box>
      </el-col>
      <el-col :span="12">
        <border-box type="gradient" variant="success">
          <div class="notice-container">
            <title-box :font-size="18" color="#67c23a">公告栏</title-box>
            <el-timeline>
              <el-timeline-item v-for="item in notices" :key="item.date" :timestamp="item.date" color="#67c23a">
                <el-tag type="success">{{ item.content }}</el-tag>
              </el-timeline-item>
            </el-timeline>
          </div>
        </border-box>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import VChart from 'vue-echarts'
import { getDashboardStats, getVisitTrend, getNotices } from '@/api/dashboard'
import { UserFilled, PieChart, Timer, List, FullScreen, Aim } from '@element-plus/icons-vue'
import { BorderBox, StatCard, TitleBox, Decoration } from '@/components/HarryData'

defineOptions({
  name: "Dashboard",
  inheritAttrs: false,
});

const stats = ref({ userCount: 0, todayVisit: 0, systemDays: 0, todoCount: 0 })
const visitOption = ref({})
const notices = ref<Array<{ date: string; content: string }>>([])
// 全屏状态
const isFullscreen = ref(false)
onMounted(async () => {
  const statsRes = await getDashboardStats()
  stats.value = statsRes || {}

  const trendRes = await getVisitTrend()
  console.log('trendRes', trendRes)
  
  // 确保数据格式正确
  let trend: { dates: string[]; counts: number[] } = { dates: [], counts: [] }
  if (trendRes && typeof trendRes === 'object') {
    // 如果返回的是完整响应对象（包含code、message、data）
    if ('data' in trendRes && trendRes.data) {
      trend = trendRes.data as { dates: string[]; counts: number[] }
    } else {
      // 如果返回的是data部分
      trend = trendRes as { dates: string[]; counts: number[] }
    }
  }
  
  console.log('处理后的trend数据:', trend)
  
  visitOption.value = {
    title: { text: '访问趋势', left: 'center', textStyle: { color: '#409eff' } },
    tooltip: { trigger: 'axis' },
    xAxis: { 
      type: 'category', 
      data: trend.dates || [], 
      boundaryGap: false,
      axisLine: { lineStyle: { color: '#ddd' } },
      axisTick: { lineStyle: { color: '#ddd' } }
    },
    yAxis: { 
      type: 'value',
      axisLine: { lineStyle: { color: '#ddd' } },
      axisTick: { lineStyle: { color: '#ddd' } },
      splitLine: { lineStyle: { color: '#f0f0f0' } }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    series: [{
      data: trend.counts || [],
      type: 'line',
      smooth: true,
      areaStyle: { 
        color: { 
          type: 'linear', 
          x: 0, y: 0, x2: 0, y2: 1, 
          colorStops: [
            { offset: 0, color: 'rgba(64, 158, 255, 0.3)' }, 
            { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
          ] 
        } 
      },
      lineStyle: { color: '#409eff', width: 3 },
      symbol: 'circle',
      symbolSize: 8,
      itemStyle: { color: '#409eff' }
    }]
  }

  const noticesRes = await getNotices()
  notices.value = noticesRes || []

  await nextTick()
  window.dispatchEvent(new Event('resize'))
  
  // 监听全屏状态变化
  document.addEventListener('fullscreenchange', handleFullscreenChange)
})

// 组件卸载时清理监听器
onUnmounted(() => {
  document.removeEventListener('fullscreenchange', handleFullscreenChange)
  // 如果组件卸载时还在全屏状态，清理样式
  if (isFullscreen.value) {
    document.body.classList.remove('dashboard-fullscreen')
  }
})


// 全屏切换（浏览器全屏 + 隐藏侧边栏和导航栏）
const toggleFullscreen = () => {
  if (!isFullscreen.value) {
    // 进入全屏
    document.documentElement.requestFullscreen().then(() => {
      isFullscreen.value = true
      document.body.classList.add('dashboard-fullscreen')
    }).catch((err) => {
      console.error('进入全屏失败:', err)
      // 即使浏览器全屏失败，也尝试隐藏侧边栏
      isFullscreen.value = true
      document.body.classList.add('dashboard-fullscreen')
    })
  } else {
    // 退出全屏
    if (document.fullscreenElement) {
      document.exitFullscreen().then(() => {
        isFullscreen.value = false
        document.body.classList.remove('dashboard-fullscreen')
      }).catch((err) => {
        console.error('退出全屏失败:', err)
        isFullscreen.value = false
        document.body.classList.remove('dashboard-fullscreen')
      })
    } else {
      isFullscreen.value = false
      document.body.classList.remove('dashboard-fullscreen')
    }
  }
}

// 监听全屏状态变化（用户按ESC退出全屏时）
const handleFullscreenChange = () => {
  if (!document.fullscreenElement && isFullscreen.value) {
    isFullscreen.value = false
    document.body.classList.remove('dashboard-fullscreen')
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  // 欢迎区域
  .welcome-box {
    margin-bottom: 20px;
  }
  
  .welcome {
    padding: 20px;
    
    .welcome-info {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 20px;
      margin-top: 20px;
      
      .welcome-desc {
        margin: 0;
        color: #909399;
        font-size: 14px;
      }
    }


      
  .fullscreen-btn {
    position: absolute;
    top: 0;
    margin: 10px;
    right: 20px;
    z-index: 100;
    background: rgba(64, 158, 255, 0.1);
    border: 1px solid rgba(64, 158, 255, 0.3);
    color: #409eff;
    transition: all 0.3s ease;
    cursor: pointer;
    pointer-events: auto;
    
    &:hover {
      background: rgba(64, 158, 255, 0.2);
      border-color: #409eff;
      transform: scale(1.1);
    }
    
    .is-dark & {
      background: rgba(0, 212, 255, 0.1);
      border-color: rgba(0, 212, 255, 0.3);
      color: #00d4ff;
      
      &:hover {
        background: rgba(0, 212, 255, 0.2);
        border-color: #00d4ff;
        box-shadow: 0 0 15px rgba(0, 212, 255, 0.4);
      }
    }
  }
  }
  
  // 图表容器
  .chart-container {
    padding: 20px;
    min-height: 400px;
  }
  
  // 公告容器
  .notice-container {
    padding: 20px;
    min-height: 400px;
    
    :deep(.el-timeline) {
      padding-top: 10px;
    }
  }
}

.mb-2 {
  margin-bottom: 20px;
}
</style>
